﻿using System;
using System.Collections.Generic;

using RexToy.UI.WinForm.ViewModel;
using RexToy.UI.WinForm.Pmlx;

namespace RexToy.UI.WinForm.Controls
{
    public class CheckBox : System.Windows.Forms.CheckBox, IDataExchange, IBindCommand
    {
        public CheckBox()
        {
            _exchange = true;
            this.Disposed += new EventHandler(CheckBox_Disposed);
        }

        void CheckBox_Disposed(object sender, EventArgs e)
        {
            if (_cmd != null)
                CommandBindRegistry.Instance().RemoveItem(this);
        }

        private IUICommand _cmd;
        public IUICommand Command
        {
            get { return _cmd; }
            set
            {
                CommandBindRegistry.Instance().PutItem(this);
                _cmd = value;
            }
        }

        public void QueryCanExecute()
        {
            if (_cmd != null)
                this.Enabled = _cmd.CanExecute();
        }

        public void UpdateModel(ViewModelBase model)
        {
            if (string.IsNullOrEmpty(BindPropertyName))
                return;
            IReflector r = Reflector.Bind(model);
            object val = TypeCast.ChangeToTypeOrNullableType(Checked, r.GetPropertyType(BindPropertyName));
            r.SetPropertyValue(BindPropertyName, val);
        }

        public void UpdateView(ViewModelBase model)
        {
            if (string.IsNullOrEmpty(BindPropertyName))
                return;
            IReflector r = Reflector.Bind(model);
            object val = r.GetPropertyValue(BindPropertyName);
            if (val != null)
            {
                bool b = (bool)val;
                Checked = b;
            }
            else
                Checked = false;
        }

        protected override void OnLostFocus(EventArgs e)
        {
            this.UpdateModelByTrigger(UpdateModelTrigger.LostFocus);
            base.OnLostFocus(e);
        }

        protected override void OnCheckedChanged(EventArgs e)
        {
            this.UpdateModelByTrigger(UpdateModelTrigger.PropertyChanged);
            base.OnCheckedChanged(e);

            if (_cmd != null)
                _cmd.Execute();
        }

        private string _bindPorpertyName;
        public string BindPropertyName
        {
            get { return this.GetBindProperty(_bindPorpertyName); }
            set { _bindPorpertyName = value; }
        }

        private UpdateModelTrigger _updateModelTrigger;
        public UpdateModelTrigger UpdateModelTrigger
        {
            get { return _updateModelTrigger; }
            set { _updateModelTrigger = value; }
        }

        private bool _exchange;
        public bool Exchange
        {
            get { return _exchange; }
            set { _exchange = value; }
        }
    }
}
